{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1bd8dc28",
   "metadata": {},
   "source": [
    "* 记录人:Lz  \n",
    "* 时间：2022-3-29  \n",
    "* week05:百度AI开放平台——图像识别  \n",
    "* 学习资源: https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02061cef",
   "metadata": {},
   "source": [
    "## 通用物体和场景识别\n",
    "\n",
    "### 接口描述\n",
    "* 该请求用于通用物体及场景识别，即对于输入的一张图片（可正常解码，且长宽比适宜），输出图片中的多个物体及场景标签。\n",
    "\n",
    "### 请求示例\n",
    "* HTTP 方法：POST\n",
    "\n",
    "### 请求URL\n",
    "* https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\n",
    "\n",
    "### 鉴权认证机制(access_token)\n",
    "* 参考：https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu\n",
    "* 获取Access Token\n",
    "* 获取access_token示例代码:  \n",
    "\n",
    "---\n",
    "* 返回值说明：  \n",
    ">> access_token： 要获取的Access Token；  \n",
    ">> expires_in： Access Token的有效期(秒为单位，有效期30天)；"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "43a5085b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.606e58f2527e40b0d6a415767eeb98cc.315360000.1963883052.282335-25863398', 'expires_in': 2592000, 'session_key': '9mzdWW7e/TCsOEP8FhruuemV6gAD8HOH1dhQJxURSo05p3p++8RFiw4UmPI2w4tOrqAyLKSvuFtThnborhNU+ImgXeX41g==', 'access_token': '24.b4bd60c6c30ea8ff1cfaab8803fb3153.2592000.1651115052.282335-25863398', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '5bc1e80a0c20c7e46ffbfe80f32bdbcd'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests\n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload ={\n",
    "        'grant_type':'client_credentials',  \n",
    "        'client_id':'bYlEQgPn5WGkzTKoMYlzQ0U',\n",
    "        'client_secret':'HF3EMNFS00S6mVhZVlBDSS7qfMmmKqj'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "79694bda",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'refresh_token': '25.606e58f2527e40b0d6a415767eeb98cc.315360000.1963883052.282335-25863398',\n",
       " 'expires_in': 2592000,\n",
       " 'session_key': '9mzdWW7e/TCsOEP8FhruuemV6gAD8HOH1dhQJxURSo05p3p++8RFiw4UmPI2w4tOrqAyLKSvuFtThnborhNU+ImgXeX41g==',\n",
       " 'access_token': '24.b4bd60c6c30ea8ff1cfaab8803fb3153.2592000.1651115052.282335-25863398',\n",
       " 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online',\n",
       " 'session_secret': '5bc1e80a0c20c7e46ffbfe80f32bdbcd'}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0cb89951",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.b4bd60c6c30ea8ff1cfaab8803fb3153.2592000.1651115052.282335-25863398'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 获取access_token\n",
    "lz_API = response.json()['access_token']\n",
    "lz_API"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2dc5336",
   "metadata": {},
   "source": [
    "* 请求参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "1cd7f4bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6afd8da4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>参数</th>\n",
       "      <th>是否必选</th>\n",
       "      <th>类型</th>\n",
       "      <th>可选值范围</th>\n",
       "      <th>说明</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>image</td>\n",
       "      <td>和url二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>url</td>\n",
       "      <td>和image二选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>baike_num</td>\n",
       "      <td>否</td>\n",
       "      <td>integer</td>\n",
       "      <td>-</td>\n",
       "      <td>返回百科信息的结果数，默认不返回</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          参数       是否必选       类型 可选值范围  \\\n",
       "0      image    和url二选一   string     -   \n",
       "1        url  和image二选一   string     -   \n",
       "2  baike_num          否  integer     -   \n",
       "\n",
       "                                                  说明  \n",
       "0  图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...  \n",
       "1  图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...  \n",
       "2                                   返回百科信息的结果数，默认不返回  "
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 图像识别 url ： https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21\n",
    "pd.read_html('https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21')[2]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3856b697",
   "metadata": {},
   "source": [
    "#### 参考代码"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5221c44",
   "metadata": {},
   "source": [
    "```\n",
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('[本地文件]', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '[调用鉴权接口获取的token]'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())\n",
    "    \n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "3af5a036",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '桥梁', 'score': 0.775434, 'root': '建筑-现代建筑'}, {'keyword': '海洋', 'score': 0.594211, 'root': '自然风景-海洋'}, {'keyword': '山峦', 'score': 0.420928, 'root': '自然风景-山峦'}, {'keyword': '天空', 'score': 0.248282, 'root': '自然风景-天空'}, {'keyword': '长城', 'score': 0.048671, 'root': '建筑-传统建筑'}], 'log_id': 1508654155572928910}\n"
     ]
    }
   ],
   "source": [
    "# 参考API文档：https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21\n",
    "# 修改原python代码\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "\n",
    "f = open('qiao.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2.酬载准备\n",
    "payload = {\n",
    "    'access_token':lz_API,\n",
    "    'image':img\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "161f818a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result': [{'name': '金边虎尾兰', 'score': 0.8310844, 'baike_info': {}}, {'name': '虎尾兰', 'score': 0.059511267, 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%99%8E%E5%B0%BE%E5%85%B0/790426', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/d01373f082025aaf28131089f2edab64034f1a4a', 'description': '虎尾兰(学名：Sansevieria trifasciata Prain)，又名虎皮兰，锦兰，千岁兰、虎尾掌、黄尾兰或岳母舌等，是百合目百合科虎尾兰属的多年生草本观叶植物。具根状茎，叶基生，肉质线状披针形，硬革质，直立，基部稍呈沟状；暗绿色，两面有浅绿色和深绿相间的横向斑带；总状花序，花白色至淡绿色；浆果直径约7-8毫米。花期11-12月。虎尾兰品种较多，株形和叶色变化较大，对环境的适应能力强。主要品种有金边虎尾兰、银脉虎尾兰。适合布置装饰书房、客厅、办公场所，可供较长时间观赏。(概述图片参考资料来源)'}}, {'name': '短叶虎尾兰', 'score': 0.004788654, 'baike_info': {}}, {'name': '龙舌兰', 'score': 0.0029926975, 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E9%BE%99%E8%88%8C%E5%85%B0/1039', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/0bd162d9f2d3572cc95eebd58713632762d0c37f', 'description': '龙舌兰(Agave americana L.)是石蒜科、龙舌兰属多年生常绿大型草本植物。叶呈莲座式排列，大型，肉质，倒披针状线形，中部宽15-20厘米，基部宽10-12厘米，叶缘具有疏刺，顶端有1硬尖刺，刺暗褐色。圆锥花序大型，长达12米，多分枝；花黄绿色；雄蕊长约为花被的2倍。蒴果长圆形。开花后花序上生成的珠芽极少。原产美洲热带；中国华南及西南各省区常引种栽培，在云南已逸生多年，且在红河、怒江、金沙江等的干热河谷地区以至昆明均能正常开花结实。叶纤维供制船缆、绳索、麻袋等，龙舌兰茎可食用，叶还可以被用来喂牲畜；温室常盆栽供观赏。(概述图参考来源：)'}}, {'name': '金边龙舌兰', 'score': 0.0013805528, 'baike_info': {}}], 'log_id': 1508755853015115125}\n"
     ]
    }
   ],
   "source": [
    "# 参考API文档：https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Mk3bcxe9i\n",
    "\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "植物识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v1/plant\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('zhiwu.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload={\n",
    "    'access_token':lz_API,\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7384908",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
